package com.llcbenwu.social;

import com.llcbenwu.security.QQproperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.SpringSocialConfigurer;

import javax.sql.DataSource;

/**
 * @author lilinchun
 * @date 2021/11/2 0002 09:51
 */
@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired(required = false)
    private ConnectionSignUp connectionSignUp;


    @Primary
    @Bean
    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        /**
         * connectionFactoryLocator连接工厂（以后可能会有许多的工厂）
         * Encryptors.noOpText() 对信息进行加解密
         */
        JdbcUsersConnectionRepository repository=new JdbcUsersConnectionRepository( dataSource,  connectionFactoryLocator, Encryptors.noOpText());
        repository.setTablePrefix("llc_");
        //判断Bean中是否有类继承了ConnectionSignUp如果有继承了
        if (connectionSignUp !=null){
            repository.setConnectionSignUp(connectionSignUp);
        }
        return repository;
    }


    @Bean
    public SpringSocialConfigurer llcSocialSecurityConfig(){
        QQproperties qQproperties=new QQproperties();
        //这里是配置了一个自定义过滤器对需要QQ互联的url进行过滤
        LlcSpringSocialConfig llcSpringSocialConfig=new LlcSpringSocialConfig(qQproperties.getFilterProcessesUrl());
        //QQ登录用户绑定账号
        llcSpringSocialConfig.signupUrl(qQproperties.getSignUpUrl());
        return llcSpringSocialConfig;
    }

    /**
     * 作用1：从springSocial中获取用户信息
     * 作用2：将用户信息传回springSocial
     * @return
     */
    @Bean
    public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator connectionFactoryLocator){
       return  new ProviderSignInUtils(connectionFactoryLocator,getUsersConnectionRepository(connectionFactoryLocator));
    }


}
